;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Enterprise.NoticeBulletin", [])
        .controller("NoticeBulletinCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", "Upload", "ybConfig", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus, Upload, ybConfig) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                allCheckedDealer: false,
                allCheckedUser: false,
                curRow: -1
            };
            //通知公告分页信息
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            //配置用户分页信息
            $scope.userPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            //配置客户分页信息
            $scope.customerPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.condition = {};
            $scope.conditionDealer = {};
            $scope.conditionUser = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
            };
            $scope.dataList = [];
            $scope.dealerDataList = [];
            $scope.userDataList = [];
            $scope.dealerDataSelectList = [];
            $scope.userDataSelectList = [];
            $scope.checkedList = [];
            $scope.isModify = false;
            $scope.detailObj = "";
            $scope.mainId = "";
            $scope.detailInfo = {
                isHeader: 0,
                isDownload: 0,
                isShow: 1,
                basicAttachmentList: []
            };
            $scope.tbConf = {
                fixedWidth: 230,
                scrollWidth: 1220,
                tableCol: [
                    {
                        type: "",
                        name: "公告标题",
                        dataField: "title",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否置顶",
                        dataField: "isHeader",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "类型",
                        dataField: "typeName",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "开始时间",
                        dataField: "validateStartStr",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结束时间",
                        dataField: "validateEndStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "链接",
                        dataField: "click",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }, {
                        type: "",
                        name: "是否显示",
                        dataField: "isShowStr",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 230,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.tbDealerConf = {
                fixedWidth: 40,
                scrollWidth: 800,
                tableCol: [
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "dealerOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户编码",
                        dataField: "dealerOrgCode",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户分类",
                        dataField: "dealerClassName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.tbUserConf = {
                fixedWidth: 40,
                scrollWidth: 500,
                tableCol: [
                    {
                        type: "",
                        name: "用户名称",
                        dataField: "userName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "所属机构",
                        dataField: "dept",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.clientSortList = [];

            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            var btnPermissionCode = {
                noticeBulletinAdd: window.ActionCode.noticeBulletinAdd,
                noticeBulletinEdit: window.ActionCode.noticeBulletinEdit,
                noticeBulletinDel: window.ActionCode.noticeBulletinDel
            };

            $scope.btnPermission = {
                noticeBulletinAdd: true,
                noticeBulletinEdit: true,
                noticeBulletinDel: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    fixedWidth: {left: $scope.tbConf.fixedWidth + "px"}
                };
            };

            $scope.setDealerFixedWidth = function () {
                $scope.tbDealerStyle = {
                    fixedWidth: {left: $scope.tbDealerConf.fixedWidth + "px"}
                };
            };

            $scope.setUserFixedWidth = function () {
                $scope.tbUserStyle = {
                    fixedWidth: {left: $scope.tbUserConf.fixedWidth + "px"}
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.mainId = "";
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMaterielOriginal = false;
                $scope.isModify = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    allCheckedDealer: false,
                    allCheckedUser: false,
                    curRow: -1
                };
                var service = "device";
                var reqUrl = "/basicAnnouncement/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.validateStartStr = $filter('YbDate')(item.validateStart, "yyyy-MM-dd");
                        item.validateEndStr = $filter('YbDate')(item.validateEnd, "yyyy-MM-dd");
                        item.click = "http://" + item.click;
                        item.isHeader = item.isHeader === 0 ? '否' : '是';
                        item.isShowStr = item.isShow === 0 ? '否' : '是';
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function getDealerDataList(curPage) {
                var service = "device";
                var reqUrl = "/basicAnnouncementAuth/listDealer";
                var param = {};
                param.pageSize = $scope.customerPageInfo.pageSize;
                if (!!curPage) {
                    $scope.customerPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.customerPageInfo.curPage;
                param.filters = angular.copy($scope.conditionDealer);
                param.filters.mainId = $scope.mainId;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.customerPageInfo.totalRows = resp.value.total;
                    $scope.customerPageInfo.totalPages = resp.value.pages;
                    $scope.dealerDataList = resp.value.list;

                    $scope.dealerDataSelectList = [];
                    var allChecked = true;
                    if(!$scope.dealerDataList || $scope.dealerDataList.length === 0) {
                        $scope.markInfo.allCheckedDealer = false;
                        $scope.checkedList = [];
                        return;
                    }
                    angular.forEach($scope.dealerDataList, function (item) {
                        if(item.isSelect){
                            item.isChecked = true;
                            $scope.dealerDataSelectList.push(item);
                        } else {
                            allChecked = false;
                            item.isChecked = false;
                        }
                    });
                    $scope.markInfo.allCheckedDealer = allChecked;
                    $scope.checkedList = angular.copy($scope.dealerDataSelectList);
                });
            }

            function getUserDataList(mainId, curPage) {
                var service = "device";
                var reqUrl = "/basicAnnouncementAuth/listUser";
                var param = {};
                param.pageSize = $scope.userPageInfo.pageSize;
                if (!!curPage) {
                    $scope.userPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.userPageInfo.curPage;
                param.filters = angular.copy($scope.conditionUser);
                param.filters.mainId = $scope.mainId;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.userPageInfo.totalRows = resp.value.total;
                    $scope.userPageInfo.totalPages = resp.value.pages;
                    $scope.userDataList = resp.value.list;

                    $scope.dealerDataSelectList = [];
                    var allChecked = true;
                    angular.forEach($scope.userDataList, function (item) {
                        if(item.isSelect){
                            item.isChecked = true;
                            $scope.dealerDataSelectList.push(item);
                        } else {
                            allChecked = false;
                            item.isChecked = false;
                        }
                    });
                    $scope.markInfo.allCheckedUser = allChecked;
                    $scope.checkedList = angular.copy($scope.dealerDataSelectList);
                });
            }

            $scope.delSign = function (code) {
                var codeList = [code];
                delFunc(codeList);
            };

            $scope.delBatch = function () {
                var codeList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        codeList.push(item.id);
                    }
                });
                delFunc(codeList);
            };

            function delFunc(CodeList) {
                if (CodeList.length == 0) {
                    ybWidget.ShowMessage('请选择要删除的数据');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    ybHttp.Post(service, '/basicAnnouncement/remove', {ids: CodeList}).then(function (data) {
                        if (data.code !== 0) {
                            ybWidget.ShowMessage(data.message);
                            return;
                        }
                        getDataList();
                    })
                })
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.searchDealer = function (curpage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    allCheckedDealer: false,
                    curRow: -1
                };
                getDealerDataList(curpage);
            };

            $scope.searchUser = function (curpage) {
                getUserDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.resetDealer = function () {
                $scope.conditionDealer = {};
            };

            $scope.resetUser = function () {
                $scope.conditionUser = {};
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }

                checkAuthModify();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                checkAuthModify();
            };


            function viewDetail(item) {
                getDataDetail(item.id).then(function (value) {
                    if (value) {
                        value.value.click = "http://" + value.value.click;
                        $scope.detailObj = value.value;
                        $scope.changeTab(2);
                    }
                });
                getEnclosureList(item.id).then(function (resp) {
                    $scope.detailInfo.basicAttachmentList = resp.value.list;
                })
            }

            var getDataDetail = function (id) {
                var service = "device";
                var reqUrl = "/basicAnnouncement/item";
                return ybHttp.Get(service, reqUrl, {id: id}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp;
                });
            };

            var getEnclosureList = function (id) {
                var service = "device";
                var reqUrl = "/basicAttachment/list";
                var param = {
                    filters: {
                        announcementId: id
                    },
                    pageNum: 1,
                    pageSize: 10
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp;
                });
            };

            //编辑按钮
            $scope.editData = function (item) {
                getDataDetail(item.id).then(function (resp) {
                    $scope.detailInfo = resp.value;
                    if (!!$scope.detailInfo.validateEnd) {
                        $scope.detailInfo.validateEnd = $filter("YbDate")($scope.detailInfo.validateEnd);
                    }
                    if (!!$scope.detailInfo.validateStart) {
                        $scope.detailInfo.validateStart = $filter("YbDate")($scope.detailInfo.validateStart);
                    }
                    return getEnclosureList(item.id)
                }).then(function (resp) {
                    $scope.detailInfo.basicAttachmentList = resp.value.list;
                    angular.forEach($scope.detailInfo.basicAttachmentList, function (listItem) {
                        listItem.announcementId = item.id;
                    });
                    $scope.tabFlag.name = tabFlag["1"];
                    $scope.tabFlag.type = 1;
                    $scope.changeTab(1);
                })
            };

            //新增按钮
            $scope.addData = function () {
                var halfYearsLater = new Date();
                halfYearsLater.setMonth(halfYearsLater.getMonth() + 6);
                $scope.detailInfo = {
                    isHeader: 1,
                    isDownload: 1,
                    isShow: 1,
                    authDealerAll: 0,
                    authUserAll: 0,
                    basicAttachmentList: [],
                    type: '1',
                    typeName: '普通公告',
                    validateStart: new Date(),
                    validateEnd: halfYearsLater
                };
                $scope.tabFlag.name = tabFlag["0"];
                $scope.tabFlag.type = 0;
                $scope.changeTab(1);
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.auth = function (mainId, type) {
                $scope.mainId = mainId;
                if(type === 'dealer'){
                    getDealerDataList();
                    $scope.changeTab(3);
                }
                if(type === 'user'){
                    getUserDataList();
                    $scope.changeTab(4);
                }
            };

            $scope.saveData = function (isValid, form) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.detailInfo.typeName !== "促销活动") {
                    $scope.detailInfo.isShow = 1;
                }
                var service = "device";
                var reqUrl = "/basicAnnouncement/add";
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/basicAnnouncement/update";
                }

                var param = angular.copy($scope.detailInfo);

                if (!!param.id) {
                    angular.forEach(param.basicAttachmentList, function (item) {
                        item.announcementId = param.id
                    })
                }
                saveData(service, reqUrl, param).then(function (value) {
                    if (value) {
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList(1);
                        $scope.changeTab(0);
                    }
                })
            };

            function saveData(service, reqUrl, param) {
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp;
                });
            }

            $scope.saveAuth = function (type) {
                var addList = [];
                angular.forEach($scope.checkedList, function (item) {
                    var flag = true;
                    for(var i=0; i<$scope.dealerDataSelectList.length; i++){
                        if(type === 'dealer' && item.dealerOrgId === $scope.dealerDataSelectList[i].dealerOrgId){
                            flag = false;
                        }
                        if(type === 'user' && item.userId === $scope.dealerDataSelectList[i].userId){
                            flag = false;
                        }
                    }
                    if(flag){
                        item.authType = type === 'user'?1:0;
                        addList.push(item);
                    }
                });

                var removeList = [];
                angular.forEach($scope.dealerDataSelectList, function (item) {
                    var flag = true;
                    for(var i=0; i<$scope.checkedList.length; i++){
                        if(type === 'dealer' && item.dealerOrgId === $scope.checkedList[i].dealerOrgId){
                            flag = false;
                        }
                        if(type === 'user' && item.userId === $scope.checkedList[i].userId){
                            flag = false;
                        }
                    }
                    if(flag){
                        removeList.push(item);
                    }
                });

                if(addList.length === 0 && removeList.length === 0){
                    ybWidget.ShowMessage("请选择客户", MESG_TYPE.Warn);
                    return;
                }

                var service = "device";
                var reqUrl = "/basicAnnouncementAuth/saveOpr";
                var param = {};
                param.addList = addList;
                param.removeList = removeList;

                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.isModify = false;
                });
            };

            $scope.searchDealerPre = function (curpage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                getDealerDataList(curpage);
            };

            function checkAuthModify(){
                $scope.checkedList = [];
                if($scope.activeFlag[3]){
                    angular.forEach($scope.dealerDataList, function (item) {
                        if(item.isChecked){
                            $scope.checkedList.push(item);
                        }
                    });
                }
                if($scope.activeFlag[4]){
                    angular.forEach($scope.userDataList, function (item) {
                        if(item.isChecked){
                            $scope.checkedList.push(item);
                        }
                    });
                }
                $scope.isModify = !compareDataList($scope.checkedList, $scope.dealerDataSelectList);
            };

            function compareDataList(list1, list2){
                if(!list1 && !list2){
                    return true;
                }
                return JSON.stringify(list1) === JSON.stringify(list2);
            }

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.uploadDoc = function (file, index) {
                if (!file) {
                    return;
                }
                /*if (file.size > FileSize.TwoMb) {
                    ybWidget.ShowMessage("请选择小于2M的文件", MESG_TYPE.Error);
                    return;
                }*/
                if (!/\.(xlsx|xls|doc|docx|pdf|zip|rar|XLSX|XLS|DOC|DOCX|PDF)$/.test(file.name)) {
                    ybWidget.ShowMessage("请选择 .xlsx .xls .doc .docx .pdf .zip .rar  格式的文件，最大不能超过50M", MESG_TYPE.Error);
                    return;
                }
                Upload.upload({
                    url: ybConfig.getConfig().baseUrl.Site + ybConfig.getConfig().serviceName.device + '/basicAnnouncement/uploadAttach',
                    data: {file: file, fileName: file.name}
                }).then(function (resp) {
                    var fileObj = {};
                    fileObj.name = resp.config.data.fileName;
                    fileObj.value = resp.data.value;
                    $scope.detailInfo.basicAttachmentList.push(fileObj);
                }, function (resp) {
                    ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                });
            };

            //删除附件
            $scope.delEnclosure = function (index) {
                $scope.detailInfo.basicAttachmentList.splice(index, 1);
            };

            $scope.downloadAttach = function (item) {
                window.location.href = ybHttp.RequestUrl("device", "/basicAnnouncement/downloadAttach") + '?name=' + item.value +"&oldName=" + item.name;
            };

            $scope.previewAttach = function (item) {
                if (item.name && item.name.endsWith('.pdf')) {
                    // 预览
                    previewPdfOnBlank("/basicAnnouncement/downloadAttach" + '?name=' + item.value +"&oldName=" + item.name, true);
                } else {
                    $scope.downloadAttach(item);
                }
            };

            function previewPdfOnBlank(url, isNoTool) {
                if (!url) {
                    return;
                }
    
                ybHttp.Get("device", url,{}, {responseType: 'arraybuffer'}).then(function (msg) {
                    var file = new Blob([msg], { type: 'application/pdf' });
                    var fileURL = URL.createObjectURL(file);
                    window.open(fileURL + (isNoTool?"#toolbar=0":""), "文档预览");
                });
            }

            function getClientSort() {
                var service = "device";
                var reqUrl = "/dealerClass/list";
                var param = {pId: "0"};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.clientSortList = resp.value;
                });
            }

            (function () {
                getDataList();
                getClientSort();
                $scope.setFixedWidth();
                $scope.setDealerFixedWidth();
                $scope.setUserFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
